package ciicos.equ.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.equ.entity.UpkeepRecordEntity;
import ciicos.equ.mapper.UpkeepRecordMapper;
import ciicos.equ.model.upkeeprecord.UpkeepRecordForm;
import ciicos.equ.model.upkeeprecord.UpkeepRecordPagination;
import ciicos.equ.service.UpkeepRecordService;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.*;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * upkeepRecord
 * 版本： V3.2.0
 * 版权：
 * 作者： 企业研发中心
 * 日期： 2024-03-12
 */
@Service
public class UpkeepRecordServiceImpl extends ServiceImpl<UpkeepRecordMapper, UpkeepRecordEntity> implements UpkeepRecordService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Override
    public List<UpkeepRecordEntity> getList(UpkeepRecordPagination upkeepRecordPagination) {
        return getTypeList(upkeepRecordPagination, upkeepRecordPagination.getDataType());
    }

    @Override
    public List<UpkeepRecordEntity> getTypeList(UpkeepRecordPagination upkeepRecordPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int upkeepRecordNum = 0;
        QueryWrapper<UpkeepRecordEntity> upkeepRecordQueryWrapper = new QueryWrapper<>();

//树形，异步父级查询条件
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(upkeepRecordPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(upkeepRecordPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int upkeepRecordNum1 = 0;
            QueryWrapper<UpkeepRecordEntity> upkeepRecordSuperWrapper = new QueryWrapper<>();
            upkeepRecordNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(upkeepRecordSuperWrapper, superQueryList, matchLogic, "F_upkeepRecord")
                    , new UpkeepRecordEntity(), upkeepRecordNum1);
            if (upkeepRecordNum1 > 0) {
                List<String> upkeepRecordList = this.list(upkeepRecordSuperWrapper).stream().map(UpkeepRecordEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(upkeepRecordList);
                intersectionSuperList.add(upkeepRecordList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = true;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object upkeepRecordObj = authorizeService.getCondition(new AuthorizeConditionModel(upkeepRecordQueryWrapper, upkeepRecordPagination.getMenuId(), "F_upkeepRecord"));
                if (ObjectUtil.isEmpty(upkeepRecordObj)) {
                    return new ArrayList<>();
                } else {
                    upkeepRecordQueryWrapper = (QueryWrapper<UpkeepRecordEntity>) upkeepRecordObj;
                    if (upkeepRecordQueryWrapper.getExpression().getNormal().size() > 0) {
                        upkeepRecordNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object upkeepRecordObj = authorizeService.getCondition(new AuthorizeConditionModel(upkeepRecordQueryWrapper, upkeepRecordPagination.getMenuId(), "F_upkeepRecord"));
                if (ObjectUtil.isEmpty(upkeepRecordObj)) {
                    return new ArrayList<>();
                } else {
                    upkeepRecordQueryWrapper = (QueryWrapper<UpkeepRecordEntity>) upkeepRecordObj;
                    if (upkeepRecordQueryWrapper.getExpression().getNormal().size() > 0) {
                        upkeepRecordNum++;
                    }
                }


            }
        }


        if (isPc) {
            if (ObjectUtil.isNotEmpty(upkeepRecordPagination.getEquname())) {
                upkeepRecordNum++;
                upkeepRecordQueryWrapper.lambda().in(UpkeepRecordEntity::getEquname, upkeepRecordPagination.getEquname());

//                List<String> idList = new ArrayList<>();
//                try {
//                    String[][] equname = JsonUtil.getJsonToBean(upkeepRecordPagination.getEquname(), String[][].class);
//                    for (int i = 0; i < equname.length; i++) {
//                        if (equname[i].length > 0) {
//                            idList.add(equname[i][equname[i].length - 1]);
//                        }
//                    }
//                } catch (Exception e1) {
//                    try {
//                        List<String> equname = JsonUtil.getJsonToList(upkeepRecordPagination.getEquname(), String.class);
//                        if (equname.size() > 0) {
//                            idList.add(equname.get(equname.size() - 1));
//                        }
//                    } catch (Exception e2) {
//                        idList.add(String.valueOf(upkeepRecordPagination.getEquname()));
//                    }
//                }
//                upkeepRecordQueryWrapper.lambda().and(t -> {
//                    idList.forEach(tt -> {
//                        t.like(UpkeepRecordEntity::getEquname, tt).or();
//                    });
//                });

            }

            if (ObjectUtil.isNotEmpty(upkeepRecordPagination.getUpkeeptime())) {
                upkeepRecordNum++;

                List UpkeeptimeList = JsonUtil.getJsonToList(upkeepRecordPagination.getUpkeeptime(), String.class);
                Long fir = Long.valueOf(String.valueOf(UpkeeptimeList.get(0)));
                Long sec = Long.valueOf(String.valueOf(UpkeeptimeList.get(1)));

                upkeepRecordQueryWrapper.lambda().ge(UpkeepRecordEntity::getUpkeeptime, new Date(fir))
                        .le(UpkeepRecordEntity::getUpkeeptime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if (ObjectUtil.isNotEmpty(upkeepRecordPagination.getUpkeeptype())) {
                upkeepRecordNum++;
                upkeepRecordQueryWrapper.lambda().in(UpkeepRecordEntity::getUpkeeptype, upkeepRecordPagination.getUpkeeptype());
//                            List<String> idList = new ArrayList<>();
//                            try {
//                                String[][] upkeeptype = JsonUtil.getJsonToBean(upkeepRecordPagination.getUpkeeptype(),String[][].class);
//                                for(int i=0;i<upkeeptype.length;i++){
//                                    if(upkeeptype[i].length>0){
//                                        idList.add(upkeeptype[i][upkeeptype[i].length-1]);
//                                    }
//                                }
//                            }catch (Exception e1){
//                                try {
//                                    List<String> upkeeptype = JsonUtil.getJsonToList(upkeepRecordPagination.getUpkeeptype(),String.class);
//                                    if(upkeeptype.size()>0){
//                                        idList.add(upkeeptype.get(upkeeptype.size()-1));
//                                    }
//                                }catch (Exception e2){
//                                    idList.add(String.valueOf(upkeepRecordPagination.getUpkeeptype()));
//                                }
//                            }
//                        upkeepRecordQueryWrapper.lambda().and(t->{
//                            idList.forEach(tt->{
//                                t.like(UpkeepRecordEntity::getUpkeeptype, tt).or();
//                                });
//                            });

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            upkeepRecordQueryWrapper.lambda().in(UpkeepRecordEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            upkeepRecordQueryWrapper.lambda().and(t -> t.in(UpkeepRecordEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(upkeepRecordPagination.getSidx())) {
            upkeepRecordQueryWrapper.lambda().orderByDesc(UpkeepRecordEntity::getCreatortime);
        } else {
            try {
                String sidx = upkeepRecordPagination.getSidx();
                UpkeepRecordEntity upkeepRecordEntity = new UpkeepRecordEntity();
                Field declaredField = upkeepRecordEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                upkeepRecordQueryWrapper = "asc".equals(upkeepRecordPagination.getSort().toLowerCase()) ? upkeepRecordQueryWrapper.orderByAsc(value) : upkeepRecordQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<UpkeepRecordEntity> page = new Page<>(upkeepRecordPagination.getCurrentPage(), upkeepRecordPagination.getPageSize());
                IPage<UpkeepRecordEntity> userIPage = this.page(page, upkeepRecordQueryWrapper);
                return upkeepRecordPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<UpkeepRecordEntity> list = new ArrayList();
                return upkeepRecordPagination.setData(list, list.size());
            }
        } else {
            return this.list(upkeepRecordQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public UpkeepRecordEntity getInfo(String id) {
        QueryWrapper<UpkeepRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UpkeepRecordEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(UpkeepRecordEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, UpkeepRecordEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(UpkeepRecordEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public String checkForm(UpkeepRecordForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        return countRecover;
    }


}
